package ro.upt.dcda.web;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.jms.JMSException;
import javax.jms.StreamMessage;
import javax.naming.NamingException;

import ro.upt.dcda.pricezone.common.JMSMediator;
import ro.upt.dcda.pricezone.common.Server;
import ro.upt.dcda.pricezone.common.StoreData;
import ro.upt.dcda.pricezone.s1.pojo.User;

import com.opensymphony.xwork2.ActionContext;

public class ViewStoresServlet {

	private String distance;
	private String name;
	private List<StoreData> stores = new ArrayList<StoreData>();

	public String execute() throws Exception {
		System.out.println("Viewing stores");
		Map<String, Object> session = ActionContext.getContext().getSession();
		User user = (User) session.get("user");
		String sid = (String) session.get("sid");
		if (user == null || sid == null) {
			return "noAuth";
		}
		try {
			double longitude = Double.valueOf(session.get("longitude")
					.toString());
			double latitude = Double
					.valueOf(session.get("latitude").toString());
			Server server = JMSMediator.getMediator().getServerByLocation(
					latitude, longitude);
			StreamMessage msg = server.createStreamMessage();
			msg.writeString("stores");
			float range;
			try {
				range = Float.valueOf(distance);
			} catch (Exception ex) {
				range = 5;
			}
			if (name == null) {
				name = "";
			}
			msg.writeString("follow");
			msg.writeString(name);
			msg.writeFloat(range);
			msg.writeDouble(longitude);
			msg.writeDouble(latitude);
			StreamMessage response = null;
			response = (StreamMessage) server.getResponseFor(msg, 60000);
			if (response == null) {
				return "def";
			}
			int nr = response.readInt();
			for (int i = 0; i < nr; i++) {
				StoreData store = new StoreData();
				store.id = response.readInt();
				store.name = response.readString();
				store.description = response.readString();
				store.location = response.readString();
				store.distance = response.readString();
				store.server = response.readString();
				stores.add(store);
			}
		} catch (NamingException e) {
			e.printStackTrace();
		} catch (JMSException e) {
			e.printStackTrace();
		}
		return "def";
	}

	public List<StoreData> getStores() {
		return stores;
	}

	public void setStores(List<StoreData> stores) {
		this.stores = stores;
	}

	public String getDistance() {
		return distance;
	}

	public void setDistance(String distance) {
		this.distance = distance;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

}
